const express = require('express')
const router = express.Router()
const Education = require('../models/Education')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')
// 创建学历指导记录
router.post('/addEducation', authMiddleware(), async (req, res) => {
  try {
    const { admissionDate, fileId, schoolName, schoolCountry, schoolCity, upgradeType, studentName, isSuccessCase } = req.body

    // 验证必要字段
    const requiredFields = ['schoolCountry', 'schoolCity', 'upgradeType']
    const missingFields = requiredFields.filter(field => !req.body[field])
    if (missingFields.length > 0) {
      return res.status(400).json({
        message: `缺少必填字段：${missingFields.join(', ')}`
      })
    }

    // 验证升学类型
    if (![1, 2, 3, 4, 5, 6, 7, 8, 9].includes(parseInt(upgradeType))) {
      return res.status(400).json({
        message: '升学类型参数错误，请使用1-9（11:专升本 2:专升硕 3:本升硕 4:幼升小 5:小升初 6:初升高 7:高升专 8:高升本 9: 硕升博）'
      })
    }

    const newRecord = new Education({
      admissionDate: admissionDate || new Date(),
      files: fileId,
      schoolName,
      schoolCountry,
      schoolCity,
      upgradeType: parseInt(upgradeType),
      studentName,
      isSuccessCase: isSuccessCase || 0
    })

    const savedRecord = await newRecord.save()
    await markFileAsReferenced(fileId)

    res.status(201).json({
      data: savedRecord,
      message: '创建成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 查询学历指导记录（支持年份/学校名字/升学类型/ID筛选）
router.get('/queryEducation', async (req, res) => {
  try {
    const { year, educationId, schoolName, upgradeType, isDomestic, studentName, pageNum = 1, pageSize = 10 } = req.query
    const filter = {}
    const options = {
      skip: (parseInt(pageNum) - 1) * parseInt(pageSize),
      limit: parseInt(pageSize),
      sort: { createdAt: -1 }
    }

    // ID查询使用_id而不是educationId
    if (educationId) {
      filter._id = educationId
    }

    // 国内/国外筛选使用schoolCountry
    if (isDomestic) {
      filter.schoolCountry = isDomestic === '1' ? '中国' : { $ne: '中国' }
    }
    if (schoolName) {
      // 模糊查询
      filter.schoolName = { $regex: schoolName, $options: 'i' }
    }
    if (studentName) {
      filter.studentName = { $regex: studentName, $options: 'i' }
    }
    if (upgradeType) {
      filter.upgradeType = upgradeType
    }
    if (year) {
      // 根据admissionDate筛选年份
      const startDate = new Date(`${year}-01-01`)
      const endDate = new Date(`${year}-12-31`)
      filter.admissionDate = {
        $gte: startDate,
        $lte: endDate
      }
      // filter.year = parseInt(year)
    }
    const [records, total] = await Promise.all([
      Education.find(filter).populate('files').skip(options.skip).limit(options.limit).sort(options.sort),
      Education.countDocuments(filter)
    ])
    console.log(records)

    res.json({
      data: records,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新学历指导记录
router.post('/updateEducation', authMiddleware(), async (req, res) => {
  try {
    const { educationId, admissionDate, fileId, schoolName, schoolCountry, schoolCity, upgradeType, studentName, isSuccessCase } = req.body
    const record = await Education.findById(educationId)

    if (!record) return res.status(404).json({ message: '记录不存在' })
    // 处理国家/城市更新
    if (schoolCountry) {
      record.schoolCountry = schoolCountry
      // 自动清除城市信息（可选）
      if (!schoolCity) record.schoolCity = ''
    }
    if (schoolCity) {
      record.schoolCity = schoolCity
    }

    // 处理升学类型更新
    if (upgradeType) {
      if (![1, 2, 3, 4, 5, 6, 7, 8, 9].includes(parseInt(upgradeType))) {
        return res.status(400).json({ message: '无效的升学类型' })
      }
      record.upgradeType = parseInt(upgradeType)
    }

    // 处理文件更新
    if (fileId && fileId !== record.files.toString()) {
      await unmarkFileReference(record.files)
      await markFileAsReferenced(fileId)
      record.files = fileId
    }

    // 更新日期
    if (admissionDate) {
      record.admissionDate = new Date(admissionDate)
    }
    // 更新学校名称和学生姓名
    Object.assign(record, { schoolName, studentName, isSuccessCase })
    const updatedRecord = await record.save()

    res.json({
      data: updatedRecord,
      message: '更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除学历指导记录
router.post('/deleteEducation', authMiddleware(), async (req, res) => {
  try {
    const record = await Education.findByIdAndDelete(req.body.educationId)
    if (!record) return res.status(404).json({ message: '记录不存在' })

    await unmarkFileReference(record.files)

    res.json({ message: '删除成功' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
